<?php
class AccountController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
    }
    
    /** Action enable login with sunnet mail **/
    public function loginAction(){
    	Zend_Loader::loadClass(LightOpenID);
    	Zend_Loader::loadClass(AuthModel);
    	$request = $this->getRequest();
    	$view = $this->view;
    	
    	//set layout
    	$layoutPath = APPLICATION_PATH  . '/templates/admin/admin';
		$option = array (	'layout' 		=> 'login_layout', 
              	        'layoutPath' 	=> $layoutPath );
		Zend_Layout::startMvc ( $option );
    	
		//check authenticated
		$auth = new AuthModel();
		if($auth->hasIdentity())
			$this->_redirect('/admin/index');
		
		try {
		    $openid = new LightOpenID;
		    
		    //not login
		    if(!$openid->mode) {
		        if($request->getParam('login')) {
		            $openid->identity = 'https://www.google.com/accounts/o8/id';
					$openid->required = array('namePerson/first', 'namePerson/last', 'contact/email');
		            header('Location: ' . $openid->authUrl());
		        }
		    
		    //user cancel
		    } elseif($openid->mode == 'cancel') {
		        echo 'User has canceled authentication!';
		           
		    } else {
		    	//login success
				if($openid->validate())
				{		
					$auth = new AuthModel();
					
					$identity = $openid->identity;
					$attributes = $openid->getAttributes();
					$email = $attributes['contact/email'];
					$first_name = $attributes['namePerson/first'];
					$last_name = $attributes['namePerson/last'];
					
					if($auth->validateUser($email)){
						$auth->setIdentity($identity, $email, $first_name, $last_name);
						$this->_redirect("/admin/index");
					}else{
						$message[] = "Can't login with $email";
						$view->error_messages = $message;	
					}
				}
				else
				{
					$view->error_messages[] = $message;
				}
		    }
		} catch(ErrorException $e) {
		    echo $e->getMessage();
		}
    }
    
    public function logoutAction(){
    	Zend_Loader::loadClass(AuthModel);
    	$auth = new AuthModel();
    	$auth->clearIdentity();
    	
    	$this->_redirect('/account/login');
    }	
}
